/**
  * Created by Joshua Conero(O'Uymas) on 2016/11/17 0017.
  * QQ: 957376074
  * E-mail: Brximl@163.com
  * ?? 错误：  Exception in thread "main" javax.crypto.IllegalBlockSizeException: Input length must be multiple of 16 when decrypting with padded cipher
  */
import java.security.SecureRandom
import javax.crypto.{Cipher, KeyGenerator}
import sun.misc.{BASE64Decoder, BASE64Encoder}
class Crypto {
  var algorithm = "AES"
  // 编码
  def encode(text:String,key:String):String = {
    val cipher = Cipher.getInstance(algorithm)
    val keyer = KeyGenerator.getInstance(algorithm)
    keyer.init(128,new SecureRandom(base64_encdoe(key).getBytes("utf-8")))
    val skey = keyer.generateKey()
    cipher.init(Cipher.ENCRYPT_MODE,skey)
    val result = cipher.doFinal(text.getBytes("utf-8"))
    new BASE64Encoder().encode(result)
  }
  // 解码
  def decode(text:String,key:String):String = {
    val cipher = Cipher.getInstance(algorithm)
    val keyer = KeyGenerator.getInstance(algorithm)
    keyer.init(128,new SecureRandom(base64_encdoe(key).getBytes("utf-8")))
    val skey = keyer.generateKey()
    cipher.init(Cipher.DECRYPT_MODE,skey)
    val result = cipher.doFinal((new BASE64Decoder).decodeBuffer(text))
    // return result.toString -> keyword is redundant 关键字是多余的
    /*
    println(new String(result))
    result.toString // 无法等到真是的数据
    */
    new String(result)
  }
  // 设置算法
  def setAlg(name:String):Unit = {algorithm = name}
  // base64 编码
  def base64_encdoe(text:String):String = {
    (new BASE64Encoder).encode(text.getBytes())
  }
  // base64 解码
  def base64_decode(text:String):String = {
    (new BASE64Decoder).decodeBuffer(text).toString
  }
}
